package uo.ri.peristence.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Date;
import java.util.List;
import java.util.Map;

import uo.ri.conf.Conf;
import uo.ri.peristence.FacturaGateway;
import alb.util.jdbc.Jdbc;

public class FacturaGatewayImpl implements FacturaGateway {
	
	private Connection connection;

	@Override
	public void setConnection(Connection con) {
		this.connection = con;
	}

	@Override
	public Long getLastInvoiceNumber() throws SQLException {
		PreparedStatement pst = null;
		ResultSet rs = null;

		try {
			pst = connection.prepareStatement(Conf.get("SQL_ULTIMO_NUMERO_FACTURA"));
			rs = pst.executeQuery();
			
			if (rs.next()) {
				return rs.getLong(1); //Devolvemos el último nº de factura
			} else {  // todavía no hay ninguna
				return null;
			}
		} finally {
			Jdbc.close(rs, pst);
		}
	}

	@Override
	public Map<String, Object> findById(Long id) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public List<Map<String, Object>> findAll() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public Long save(Map<String, Object> invoice) throws SQLException {
		long numeroFactura = (Long) invoice.get("numeroFactura");
		Date fechaFactura = (Date) invoice.get("fechaFactura");;
		double iva = (Double) invoice.get("iva");;
		double totalConIva = (Double) invoice.get("totalConIva");;
		PreparedStatement pst = null;

		try {
			pst = connection.prepareStatement(Conf.get("SQL_INSERTAR_FACTURA"));
			pst.setLong(1, numeroFactura);
			pst.setDate(2, new java.sql.Date(fechaFactura.getTime()));
			pst.setDouble(3, iva);
			pst.setDouble(4, totalConIva);
			pst.setString(5, "SIN_ABONAR");

			pst.executeUpdate();

			return getGeneratedKey(numeroFactura); // Id de la nueva factura generada
			
		} finally {
			Jdbc.close(pst);
		}
	}

	@Override
	public void delete(Long id) {
		// TODO Auto-generated method stub

	}

	@Override
	public void update(Map<String, Object> invoice) {
		// TODO Auto-generated method stub

	}

	@Override
	public Map<String, Object> findByNumber(Long number) {
		// TODO Auto-generated method stub
		return null;
	}
	
	private long getGeneratedKey(long numeroFactura) throws SQLException {
		PreparedStatement pst = null;
		ResultSet rs = null;

		try {
			pst = connection.prepareStatement(Conf.get("SQL_RECUPERAR_CLAVE_GENERADA"));
			pst.setLong(1, numeroFactura);
			rs = pst.executeQuery();
			rs.next();

			return rs.getLong(1);
			
		} finally {
			Jdbc.close(rs, pst);
		}
	}

}
